<template>
<div class="file">
  <el-upload :ref="fileRef" :action="action" :headers="headers" :data="data" :multiple="multiple" :name="name" :show-file-list="showFileList" :before-upload="beforeUpload" :before-remove="beforeRemove" :on-remove="handleRemove" :on-change="handleChange" :on-success="onSuccess" :on-error="onError" :auto-upload="autoUpload" :disabled="disabled" :limit="limit" :on-exceed="handleExceed" :accept="accept" :acceptType="acceptType" :on-preview="handleDownLoad" :http-request="httpRequest" :file-list="defaultFileList" class="upload-demo">
    <el-button size="mini" slot="trigger" type="upload" icon="iconfont icon-icon_upload">上传附件</el-button>
    <span v-if="tipText!==''" slot="tip" :class="tipStyle" v-text="tipText" />
  </el-upload>
  <el-image-viewer v-if="isShowPreviewSrc" :on-close="closeViewer" :url-list="srcList" :file-list="downFileList" :initialIndex="initialIndex" />
  <!--<ul class="el-upload-list el-upload-list&#45;&#45;text" v-show="fileList.length>0">
        <li tabindex="0" class="el-upload-list__item is-success" v-for="(item,index) in fileList" :key="index" @click.stop.prevent="handleDownLoad(item)">
            <a class="el-upload-list__item-name" style="padding-left: 120px;">
                <i class="el-icon-document"></i>
                {{item.fileName}}
            </a>
            <label class="el-upload-list__item-status-label">
                <i class="el-icon-upload-success el-icon-circle-check"></i>
            </label>
            <i class="el-icon-close" @click.stop.prevent="deleteItem(item,index)"></i>
        </li>
    </ul>-->
  <!--docx -->
  <div class="docx">
    <el-dialog :visible="showDoc == true" :show-close="true" :width="'100%'" class="dialog-div-pre-style" :before-close="closePreviewClick" center style="z-index:999999">
      <div class="dialog-body-content-base-style">
        <span class="el-image-viewer__btn el-image-viewer__close" @click="close">
          <i class="el-icon-close"></i>
        </span>
        <span class="el-image-viewer__btn el-image-viewer__down" @click="down">
          <i class="el-icon-download"></i>
        </span>
        <div class="my-component" ref="file">
        </div>
      </div>
    </el-dialog>
  </div>
  <!-- pdf -->
  <el-dialog :visible="showPdf == true" :show-close="true" :width="'100%'" class="dialog-div-pre-style" :before-close="closePreviewClick" center style="z-index:999999">
    <div class="dialog-body-content-base-style" style="justify-content: center; align-items: center">
      <span class="el-image-viewer__btn el-image-viewer__close2" @click="close">
        <i class="el-icon-close"></i>
      </span>
      <iframe :src="pdfUrl" style="width: 100%; height: 100%;z-index: 9999" />
    </div>
  </el-dialog>
</div>
</template>

<script>
//  上传
function noop() {}
// 引入docx-preview插件
let docx = require("docx-preview");
import axios from 'axios';
import {
  fileType
} from '../../constant/fileType.js';
import messageUtil from '@/utils/messageUtil.js';
// 导入组件
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  name: "Upload",
  components: {
    ElImageViewer
  },
  props: {
    businessType: {
      type: String,
    },
    fileRef: {
      type: String,
      default: "fileRef"
    },
    tipText: {
      type: String,
      default: ""
    },
    tipStyle: {
      type: String,
      default: "tip-text"
    },
    action: {
      type: String,
      required: true
    },
    headers: {
      type: Object,
      default () {
        return {};
      }
    },
    data: {
      type: Object,
      default () {
        return {};
      }
    },
    acceptType: {
      type: String,
      default: ""
    },
    /*accept: {
        type: String,
        default: ""
    },*/
    multiple: {
      type: Boolean,
      default: true
    },
    name: {
      type: String,
      default: "file"
    },
    showFileList: {
      type: Boolean,
      default: true
    },
    /*beforeUpload: {
        type: Function,
        default: noop
    },*/
    beforeRemove: {
      type: Function,
      default: noop
    },
    /*onRemove: {
        type: Function,
        default: noop
    },*/
    /*onChange: {
        type: Function,
        default: noop
    },*/
    onSuccess: {
      type: Function,
      default: noop
    },
    onError: {
      type: Function,
      default: noop
    },
    fileList: {
      type: Array,
      default () {
        return [];
      }
    },
    delList: {
      type: Array,
      default () {
        return [];
      }
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 20
    },
    /*onExceed: {
        type: Function,
        default: this.handleExceed
    },*/
    /*onPreview: {
        type: Function,
        default: noop
    },*/
    onDelete: {
      type: Function,
      default: noop
    },
    /*httpRequest: {
        type: Function,
        default: noop
    }*/
  },
  data() {
    return {
      docxFile: '',
      docxUrl: '',
      pdfUrl: '',
      // 预览文档
      showDoc: false,
      //预览PDF
      showPdf: false,
      //预览视频
      showVideo: false,
      initialIndex: 0,
      isShowPreviewSrc: false,
      srcList: [],
      downFileList: [],
      //当前文件
      currentFile: {},
      //当前文件list
      currentFileList: [],
      //默认显示文件list
      defaultFileList: [],
      accept: '',
    }
  },
  created() {
    this.getFileType();
  },
  watch: {
    fileList() {
      this.defaultFileList = this.fileList
      this.defaultFileList.map(item => item.name = item.fileName)
    }
  },
  methods: {
    close() {
      this.showDoc = false
      this.showPdf = false
    },
    down() {
      this.downloadFile(this.docxFile)
    },
    handleChange(file, fileList) {
      this.currentFile = file
      this.currentFileList = fileList
    },
    handleExceed(files, fileList) {
      messageUtil.warning('上传文件不能超过' + this.limit + '个')
    },
    getFileType() {
      if (fileType[this.acceptType] != undefined) {
        this.accept = fileType[this.acceptType]
      } else {
        this.accept = ''
      }
    },
    handleRemove(file, fileList) {
      let obj = {};
      let index = 0;
      this.fileList.filter((item, i) => {
        if (item.fileId == file.fileId) {
          obj = item
          index = i
        }
      })
      this.fileList.splice(index, 1)
      this.delList.push(obj)
      this.$emit('deleteAttch', index)
    },
    beforeUpload(file, value) {
      const isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 100MB!',
          type: 'warning'
        });
        return false
      }
      if (this.flag == 1) {
        this.$message.error('审核完成，无法继续上传~')
        return false
      }
    },
    //附件上传
    httpRequest(params) {
      this.$notify.info({
        title: '提示',
        message: '文件正在上传'
      });
      let file = params.file
      let FormDatas = new FormData()
      FormDatas.append('fileArray', file)
      FormDatas.append('businessType', this.businessType) //文件夹名称
      FormDatas.append('businessGid', "");

      this.$request({
        url: '/tos/api/file/upload',
        method: 'post',
        loading: false,
        params: FormDatas
      }).then(res => {
        if (res.code === '00000000') {
          this.$notify.success({
            title: '成功',
            message: '文件上传成功'
          });
          this.currentFile.fileId = res.data[0].fileId
          this.fileList.push({
            fileName: file.name,
            fileId: res.data[0].fileId
          })
        }
      })
    },
    handleDownLoad(file) {
      console.log('点击', file)
      this.docxFile = ''
      this.pdfUrl = ''
      this.docxUrl = ''
      this.srcList = []
      this.downFileList = []
      let idsArr = []
      let type = file.fileName.substring(file.fileName.lastIndexOf('.') + 1, file.fileName.length)
      //图片可预览
      if (['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(type.toLowerCase()) > -1) {
        this.fileList.forEach((item, index) => {
          let itemType = item.fileName.substring(item.fileName.lastIndexOf('.') + 1, item.fileName.length)
          //图片可预览
          if (['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(itemType.toLowerCase()) > -1) {
            idsArr.push(item.fileId)
            this.downFileList.push(item)
            console.log("======idsArr")
            console.log(idsArr)
          }
        })
        this.initialIndex = idsArr.indexOf(file.fileId)
        //获取文件路径
        this.$request({
          url: '/tos/api/file/getFileUrlList?idList=' + idsArr.join(","),
          method: 'get',
          loading: false,
        }).then(res => {
          if (res.code === '00000000') {
            let pathList = []
            res.data.forEach(path => {
              // pathList.push('http://172.16.8.9:9016/ypPhotos/' + path);

              console.log("path============"+path)
            pathList.push('http://172.18.21.31:81/yppms/' + path);

            })
            this.srcList = pathList
            console.log(this.srcList)
          }
        })
        this.isShowPreviewSrc = true
        //pdf可预览
      } else if (['pdf'].indexOf(type.toLowerCase()) > -1) {
        console.log("PDF")
        //获取文件路径
        this.$request({
          url: '/api/file/getFileUrlList?idList=' + file.fileId,
          method: 'get',
          loading: false,
        }).then(res => {
          if (res.code === '00000000') {
            let pathList = []
            console.log("res.data")
            console.log(res.data)
            this.pdfUrl = '//172.16.8.9:9016/ypPhotos/' + res.data[0]
            // res.data.forEach(path => {
            //   console.log("path")
            //   console.log(path)
            //   // pathList.push('http://172.16.8.9:9016/ypPhotos/' + path);
            // })
            console.log(this.pdfUrl)
          }
        })
        this.showPdf = true
        // docx可预览
      } else if (['docx'].indexOf(type.toLowerCase()) > -1) {
        this.docxFile = file
        console.log("docx")
        //获取文件路径
        this.$request({
          url: '/api/file/getFileUrlList?idList=' + file.fileId,
          method: 'get',
          loading: false,
        }).then(res => {
          if (res.code === '00000000') {
            let pathList = []
            res.data.forEach(path => {
              console.log("path")
              console.log(path)
              pathList.push('http://172.16.8.9:9016/ypPhotos/' + path);
            })
            this.docxUrl = pathList[0]
            axios({
                url: `${this.docxUrl}`,
                responseType: 'blob', // 必须设置下载文件的类型 blob 或者 arraybuffer
              })
              .then(res => {
                console.log("res")
                console.log(res)
                docx.renderAsync(res.data, this.$refs.file);
              });
            console.log(pathList[0])
          }
        })
        this.showDoc = true
      } else {
        //非图片--下载
        this.downloadFile(file)
      }
    },
    downloadFile(file) {
      this.$http.downloadFile(file.fileId, file.fileName)
    },
    closeViewer() {
      this.isShowPreviewSrc = false
    },
    //关闭
    closePreviewClick() {
      if (this.showDoc == true) {
        this.showDoc = false
      } else if (this.showPdf == true) {
        this.showPdf = false
      } else if (this.showVideo == true) {
        this.showVideo = false
      }
    },
  },
  mounted() {

  }
};
</script>

<style lang="less" scoped>
.file {
  /deep/ .el-dialog__wrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    margin: 0;
  }

  /deep/ .el-dialog {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    z-index: 999999;
    margin-top: 0vh !important;
    background:rgba(26, 25, 25, 0.5)
  }

  /deep/ .el-dialog__headerbtn {
    font-size: 0px !important;
  }

  /deep/ .el-dialog__header {
    // height: 50px;
    // line-height: 50px;
    padding: 0px;
    // border-bottom: #e1e4eb solid 1px;
    // background: #F5F7FA;
    // box-sizing: border-box;
    // font-size: 16px;
    // color: #354052;
  }

  // /deep/ .el-dialog__title {
  // line-height: 28px;
  // font-size: 18px;
  // color: black;
  // font-weight: 500;
  // float: left;
  // padding-left: 15px;
  // }

  /deep/ .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding: 0px !important;
    background:rgba(26, 25, 25, 0.5)
  }

  /deep/ .docx-wrapper {
    padding: 0px 110px !important;
    background:rgba(26, 25, 25, 0.5)
  }

  .dialog-body-content-base-style {
    height: 100%;
    z-index: 9999 !important;
  }

  .video-player {
    height: 100% !important;
  }

  /deep/ .video-js {
    height: 100% !important;
  }

  /deep/ .docx {
    width: 100% !important;
    margin-bottom: 0px !important
  }

  /deep/ ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    background: transparent;
  }

  /deep/ .el-dialog__wrapper::-webkit-scrollbar-thumb {
    border-radius: 16px;
    background-color: rgba(215, 215, 215, 0.6);
  }

  /deep/ .el-dialog__wrapper::-webkit-scrollbar-thumb:hover {
    background-color: rgba(195, 195, 195, 0.6);
  }

  /deep/ .el-dialog__wrapper::-webkit-scrollbar-thumb:active {
    background-color: rgba(175, 175, 175, 0.6);
  }

  /deep/ .el-dialog__wrapper::-webkit-scrollbar-button {
    background: transparent;
    height: 0;
  }

  /deep/ .el-image-viewer__close {
    top: 70px;
    right: 160px;
    width: 40px;
    height: 40px;
    font-size: 24px;
    color: #fff;
    background-color: #606266;
  }

  /deep/ .el-image-viewer__close2 {
    top: 19px;
    right: 146px;
    font-size: 24px;
    color: #fff;
  }

  /deep/ .el-image-viewer__down {
    top: 70px;
    right: 220px;
    width: 40px;
    height: 40px;
    font-size: 24px;
    color: #fff;
    background-color: #606266;
  }
}
.docx{
  /deep/ .el-dialog__header {
    padding: 25px;
  }
}
</style><style>
.v-modal {
  z-index: 0 !important;
}

#app .sidebar-container {
  z-index: 0 !important;
}
</style>
